<template>
	<view class="contes fontfamly">
		<view class="container">
			<view>
				<view class="flex items-center" :style="[{'height': 32 + 'px', 'margin-top': demoinfo.top + 'px'}]">
					<view class="title fontfamly">
						{{store.logotype==1?'点老板':'咚点西点'}}
					</view>
					<view class="addres flex items-end h-[64rpx] pb-[4rpx]" @click="gotochoseaddress">
						<view class="flex">
							<view class="text-[#404148] flex w-[260rpx]  text-[30rpx]">
								<view class="relative top-[2rpx]">
									<image src="../../static/my/address.svg" class="w-[30rpx] h-[30rpx]" mode="">
									</image>
								</view>
								<view class="line-clamp-1 relative bottom-[2rpx] ml-[8rpx] fontfamly">
									{{store.addressname}}
								</view>
								<view :class="store.addressname.length>6?'relative  right-[20rpx]':''"
									class="flex items-center">
									<view class="ml-[10rpx] flex items-center">
										<image src="../../static/homeimg/bottomdown.svg" class="w-[24rpx] h-[24rpx]"
											mode=""></image>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
				<view class="flex serchbox">
					<view class="u-search-inner">
						<uv-input placeholder="请输入商家或商品名称" shape="circle" v-model="inputserch"
							style="background-color: #fff;" border="none" prefixIcon="search" clearable
							@clear="getshoplistclear">
							<template #prefix>
								<!-- <image src="../../static/homeimg/search.svg" class="w-[26rpx] h-[26rpx]" mode=""></image> -->
								<view class="flex items-center pl-[20rpx] boderedous">
									<view class="">
										<uv-icon name="scan" size="44rpx" @click="geterwm"></uv-icon>
									</view>
									<!-- 	<view
										class="text-[#efefef] relative bottom-[6rpx] text-[28rpx] ml-[6rpx] mr-[4rpx]">
										|
									</view> -->
									<view
										class="bg-[#efefef] w-[1px] h-[28rpx]  flex items-center text-[28rpx] ml-[6rpx] leading-[44rpx] mr-[4rpx]">
									</view>
								</view>
							</template>
							<template v-slot:suffix>
								<view class="sureserch bg-[#FE861C]  text-[#fff]" @click="getshoplist">
									搜索
								</view>
							</template>
						</uv-input>
					</view>

				</view>
				<view class="classlist">
					<view class="flex fathscoll text-[#262934]">
						<view class="mrl-right" v-for="(item,index) in classlist.list" :key="index"
							@click="typechose(item.id)">
							<view class="imagebox mt-[40rpx]" :class="typeId==item.id?'activeimagebox':''">
								<view class="">
									<image :src="item.catePic" class=""
										:class="item.id==0?'w-[65rpx] h-[52rpx] relative top-[6rpx]':'w-[88rpx] h-[65rpx] relative top-[6rpx]'"
										mode="aspectFit"></image>
								</view>
							</view>
							<view class="classtitle" :class="typeId==item.id?'text-[#FE861C]':''">
								{{item.cateName}}
							</view>
						</view>
					</view>
				</view>
				<!-- <view class="" v-if="islogin"> -->
				<view class="">
					<view class="buliselist" v-if="bulisslist.list.length>0">
						<view v-for="(item,index) in bulisslist.list"
							class="py-[20rpx] mb-[20rpx] rounded-[30rpx] bg-[#fff] px-[20rpx]" :key="index"
							@click="getdetalbus(item)">
							<view class="flex">
								<view class="bulisimg rounded-[10rpx] relative">
									<!-- <image :src="" class="buliselimg" mode=""></image> -->
									<up-image :show-loading="true" :src="thumbImg(item.doorstepPhoto)" radius="10rpx"
										width="184rpx" height="184rpx" class="buliselimg">
										<template #error>
											<up-image :show-loading="true" :src="errjimg" radius="15rpx" width="184rpx"
												height="184rpx" class="buliselimg" mode="aspectFit">
											</up-image>
										</template>
									</up-image>
									<view
										class="absolute top-0 text-[24rpx] w-[100%] text-center bg-[#d4d4d4] rededrl py-[6rpx]"
										v-if="item.distance>item.deliveryRatio && item.businessStatus==1">
										超出配送范围
									</view>
									<view
										class="absolute top-0 text-[24rpx] w-[100%] text-[#FE861C] text-center rededrl bg-[#d4d4d4]  py-[6rpx]"
										v-if="item.businessStatus==2">
										休息中
									</view>
								</view>
								<view class="bulistext">
									<view class="buliseltitle">
										{{item.storeName}}
									</view>
									<view class="flex textmoneytime">
										<view class="numsho colorchese">
											月售 {{getsanum(item.monthSales)}}
										</view>
										<view class="flex">
											<view class="mr-[10rpx] relative top-[2rpx]">
												<image src="../../static/homeimg/time.svg" class="w-[24rpx] h-[24rpx]"
													mode="aspectFit"></image>
											</view>
											<view class="mr-[10rpx] center">
												{{item.deliverTime}}分钟
											</view>
											<view class="center">
												{{item.distance>1?item.distance+'km':item.distance*1000+'m'}}
											</view>
											<!-- 	<uv-text prefixIcon="clock" iconStyle="font-size: 12px" color="#666A7C"
											size="24rpx" :text="'\u00A0'+'30分钟 ' + item.distance+'km'"></uv-text> -->
										</view>
									</view>
									<view class="flex textmoneytime">
										<view class="numsho colorhuise">
											起送 ￥{{item.startDeliveryPrice}} | 配送费 ￥{{item.deliveryPrice}}
										</view>
									</view>
									<!-- 			<view class="small flex">
										<view class="flex boderred">
											<view class="smalltext">
												减
											</view>
											<view class="textsm">
												30减4
											</view>
											<view class="w-[2rpx] h-[22rpx] opacity-[0.3] bg-[#FF2626]">
											</view>
											<view class="textsm">
												50减7
											</view>
											<view class="w-[2rpx] h-[22rpx] opacity-[0.3] bg-[#FF2626]">
											</view>
											<view class="textsm">
												80减12
											</view>
										</view>
									</view> -->
								</view>
							</view>
						</view>
					</view>
					<view class="mt-[300rpx]" v-else>
						<view class="flex justify-center items-center">
							<image class="w-[320rpx] h-[300rpx]" src="../../static/homeimg/datanull.png"
								mode="aspectFit">
							</image>
						</view>
						<view class="flex text-[30rpx] text-[#999] justify-center items-center"
							v-if="store.lat!=='' || islocation">
							暂无数据
						</view>
						<view
							class="bg-[#FE861C] text-[#fff] w-[200rpx] px-[20rpx] text-center rounded-[20rpx] py-[10rpx] m-auto"
							@click="gotoaddress" v-if="!islocation && store.lat==''">
							设置地址
						</view>
					</view>
				</view>
				<!-- <view class="nologin" v-else>
					<view class="">
						<image src="@/static/homeimg/datanull.png" class="w-[304rpx] h-[244rpx]" mode="aspectFit">
						</image>
					</view>
					<view class="nologinmsg">
						还未收藏门店，请去收藏门店
					</view>
				</view> -->
			</view>

		</view>
	</view>
</template>

<script setup>
	import {
		thumbImg
	} from "@/utils/Server/imagescale.js"
	import errjimg from "@/static/imagenullerr.jpg"
	const demoinfo = uni.getMenuButtonBoundingClientRect()
	import {
		storegoodslist,
		storestores,
		storetype
	} from '@/api/home.js'
	import {
		onShow,
		onLoad
	} from "@dcloudio/uni-app"
	import {
		reactive,
		ref,
		watch
	} from 'vue';
	import {
		useStore
	} from '@/stores/user.js'
	const store = useStore();
	import {
		storeToRefs
	} from 'pinia'
	let {
		lat,
		lng,
		addressname
	} = store;
	const latchange = ref('')
	watch(latchange, (newVal, oldVal) => {
		latitude.value = store.lat; // 维度
		longitude.value = store.lng; // 经度
		getshoplist()
	})
	//商家列表
	const bulisslist = reactive({
		list: []
	})
	const typeId = ref('')
	const typechose = (id) => {
		typeId.value = id
		getshoplist()
	}
	onShow(() => {
		getshoplist()
		// 获取小程序更新机制兼容
		if (wx.canIUse('getUpdateManager')) {
			const updateManager = wx.getUpdateManager()
			updateManager.onCheckForUpdate(function(res) {
				// 请求完新版本信息的回调
				if (res.hasUpdate) {
					updateManager.onUpdateReady(function() {
						wx.showModal({
							title: '更新提示',
							content: '新版本已经准备好，是否重启应用？',
							success: function(res) {
								if (res.confirm) {
									// 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
									updateManager.applyUpdate()
								}
							}
						})
					})
					updateManager.onUpdateFailed(function() {
						// 新的版本下载失败
						wx.showModal({
							title: '已经有新版本了哟~',
							content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~',
						})
					})
				}
			})
		} else {
			// 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
			wx.showModal({
				title: '提示',
				content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
			})
		}
	})
	const inputserch = ref("")
	const getshoplistclear = () => {
		inputserch.value = ''
		getshoplist()
	}
	const getshoplist = () => {
		storestores({
			lng: store.lng,
			lat: store.lat,
			categoryId: typeId.value,
			search: inputserch.value,
			page: 1,
			limit: 10,
		}).then(res => {
			if (res.code == 200) {
				bulisslist.list = res.result.data
				console.log(res.result.data, "列表")
			}
		})
	}
	//跳转登录页
	const tologin = () => {
		uni.navigateTo({
			url: "/pages/login/login"
		})
	}
	//商家分类列表
	const classlist = reactive({
		list: []
	})
	//已售数量展示
	const getsanum = (e) => {
		switch (true) {
			case e <= 100:
				return e;
			case e <= 1000:
				return parseInt(e / 100)*100 + '+';
			case e <= 10000:
				return parseInt(e / 1000)*1000 + '+';
			case e > 10000:
				return 9999 + '+';
		}
	}
	//设置地址
	const gotoaddress = () => {
		uni.navigateTo({
			url: "/pages/index/address"
		})
	}
	const getclasslist = () => {
		storetype().then(res => {
			if (res.code == 200) {
				classlist.list = res.result
				classlist.list.unshift({
					cateName: "全部",
					catePic: "../../static/homeimg/alltype.png",
					id: "",
					parentId: 0
				})
			}
		}).catch(err => {
			console.log(err)
		})
	}
	import {
		useAppStore
	} from '@/stores/app.js'
	//扫描 
	const geterwm = () => {
		// uni.navigateTo({
		// 	url:"/pages/index/followinterest"
		// })
		uni.scanCode({
			onlyFromCamera: true,
			success: function(res) {
				const arr = res.result.split("=")
				useAppStore().getcategory(arr[1], 0, arr[1], 1)
				// uni.request({
				// 	url:"https://api.weixin.qq.com/wxa/query_urllink",
				// 	method:"POST",
				// 	data:{
				// 		access_token:uni.getStorageSync('loginTokenKey'),
				// 		url_link:'9L7lpeSCuFs'
				// 	},
				// 	success(res) {
				// 		console.log(res)
				// 	},
				// 	fail(err) {
				// 		console.log(err)
				// 	}
				// })
				console.log('条码内容：' + res.result);
			}
		});
	}

	//前往商家
	const getdetalbus = (item) => {
		// uni.navigateTo({
		// 	url: "/page_index/storedetals?id=" + item.id + '&deliveryPrice=' + item.deliveryPrice
		// })
		useAppStore().getcategory(item.id, item.deliveryPrice)
	}
	//选择地址 
	const gotochoseaddress = () => {
		uni.navigateTo({
			url: "/pages/index/address"
		})
	}
	const islogin = ref(false)
	const latitude = ref('')
	const longitude = ref('')
	const islocation = ref(true) //是否开启定位
	//获取定位
	const getlocations = () => {
		uni.getLocation({
			type: 'gcj02',
			altitude: true,
			success: function(res) {
				let locations = `${res.longitude},${res.latitude}`;
				latitude.value = res.latitude; // 维度
				longitude.value = res.longitude; // 经度
				uni.request({
					url: 'https://restapi.amap.com/v3/geocode/regeo?parameters',
					data: {
						key: '87400ef66791d249381bdb0e0b33db30',
						location: locations,
					},
					success: function(ress) {
						// console.log(ress.data.regeocode.addressComponent.city, '逆地理编码')
						uni.setStorage({
							key: 'City_Name',
							data: ress.data.regeocode.addressComponent.city
						})
					},
					fail: function(err) {
						uni.showToast({
							title: "获取位置信息失败",
							icon: "none"
						})
					}
				});
				uni.request({
					url: 'https://restapi.amap.com/v3/geocode/regeo',
					data: {
						key: '87400ef66791d249381bdb0e0b33db30',
						location: locations,
						radius: '1000',
						extensions: 'all'
					},
					success: function(ress) {
						store.addressname = ress.data.regeocode.pois[0].name
						let arrs = ress.data.regeocode.pois[0].location.split(',')
						store.lat = arrs[1]
						store.lng = arrs[0]
						getshoplist()
					},
					fail: function(err) {
						console.error('获取地址列表失败', err);
					}
				});
			},
			fail: function(err) {
				uni.showToast({
					title: "获取位置信息失败",
					icon: "none"
				})
				console.error('获取位置信息失败', err);
			}
		});
	}
	onShow(() => {
		latchange.value = store.lat
		if (uni.getStorageSync('loginTokenKey') !== '') {
			islogin.value = true
		} else {
			islogin.value = false
		}
		getclasslist()
		if (store.lat !== "") {
			getshoplist()
		} else {
			wx.getSetting({

				success: (res) => {
					let authSetting = res.authSetting
					if (authSetting['scope.userLocation']) {
						islocation.value = true
						if (store.getinmin == 0 || store.getinmin == 1) {
							getlocations()
							store.getinmin++
						}
					} else if (authSetting['scope.userLocation'] === false) {
						islocation.value = false
						if (store.getinmin == 0) {
							wx.showModal({
								title: '您未开启地理位置授权',
								content: '请在系统设置中打开位置授权，以便我们为您提供更好的服务',
								success: (res) => {
									if (res.confirm) {
										wx.openSetting()
									}
								}
							})
							store.getinmin++
						}

					} else {
						if (store.getinmin == 0) {
							wx.authorize({
								scope: 'scope.userLocation',
								success: () => {
									islocation.value = true
									if (store.getinmin == 0 || store.getinmin == 1 && store
										.lat == "") {
										getlocations()
										store.getinmin++
									}
								},
								fail: () => {
									islocation.value = false
									if (store.getinmin == 0) {
										wx.showModal({
											title: '您未开启地理位置授权',
											content: '请在系统设置中打开位置授权，以便我们为您提供更好的服务',
											success: (res) => {
												if (res.confirm) {
													wx.openSetting()
												}
											}
										})
										store.getinmin++
									}
								}
							})
						}

					}
				}
			})

		}

	})
	onLoad(() => {
		// getlocations()
	})
</script>

<style lang="scss" scoped>
	.nologin {
		width: 100%;
		display: flex;
		margin-top: 260rpx;
		align-items: center;
		justify-content: center;
		flex-direction: column;

		.nologinmsg {
			font-size: 28rpx;
			font-family: PingFang SC;
			font-weight: 400;
			color: #999999;
			line-height: 35rpx;
			// padding-top: 22rpx;
		}

		.tologin {
			width: 412rpx;
			height: 98rpx;
			background: #FE861C;
			border-radius: 20rpx;
			font-size: 32rpx;
			font-family: PingFang SC;
			font-weight: 500;
			color: #FFFFFF;
			line-height: 98rpx;
			text-align: center;
		}
	}

	.mb20 {
		margin-bottom: 20rpx;
	}

	.colorhuise {
		color: #666A7C;
	}

	.colorchese {
		color: #FE861C;
	}

	.colorred {
		color: #FF2626;
	}

	.buliselist {
		margin-top: 20rpx;
		// padding: 20rpx;
		margin-bottom: 40rpx;
		border-radius: 30rpx;

		.buliselimg {
			width: 184rpx;
			height: 184rpx;
		}

		.bulistext {
			width: 100%;
			margin-left: 20rpx;
			gap: 20rpx;
			display: flex;
			flex-direction: column;
			// justify-content: space-between;

			.buliseltitle {
				font-size: 32rpx;
				font-family: PingFang SC;
				line-height: 32rpx;
				font-weight: bold;
				color: #202020;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
			}

			.textmoneytime {
				font-size: 24rpx;
				line-height: 24rpx;
				justify-content: space-between;

				.numsho {
					font-size: 24rpx;
					line-height: 24rpx;
					margin-right: 40rpx;
				}
			}

			.boderred {
				border: 1rpx solid #FF2626;

				@media(min-device-pixel-ratio: 2) {
					border-width: 0.5px;
				}

				border-radius: 10rpx;
				border-width: 0.5px;
				height: 36rpx;
				font-size: 24rpx;
				color: #FF2626;
				display: flex;
				align-items: center;

				.smalltext {
					background-color: #FF2626;
					line-height: 36rpx;
					color: #fff;
					padding: 0 10rpx;
					border-bottom-left-radius: 10rpx;
					border-top-left-radius: 10rpx;
				}

				.textsm {
					padding: 0 15rpx;
				}
			}
		}
	}

	.classlist {
		// width: 100%;
		overflow: hidden;
		background-color: #fff;
		margin-top: 20rpx;
		padding: 0 20rpx;
		border-radius: 30rpx;

		.classimg {
			margin-top: 40rpx;

		}

		.fathscoll {
			// width: 100%;
			overflow-x: scroll;
		}

		.mrl-right {
			margin-right: 40rpx;
		}

		.classtitle {
			font-size: 26rpx;
			font-family: PingFang SC;
			padding-top: 18rpx;
			// width: 120rpx;
			padding-bottom: 30rpx;
			white-space: nowrap;
			text-align: center;
		}
	}

	.container {
		margin: 0 20rpx;
		width: calc(100% - 40rpx);
	}

	.sureserch {
		white-space: nowrap;
		height: 56rpx;
		display: flex;
		align-items: center;
		margin-left: 20rpx;
		font-size: 36rpx;
		font-size: 28rpx;
		padding: 0 30rpx;
		border-radius: 40rpx;
		margin-right: 10rpx;
	}

	.serchbox {
		margin-top: 20rpx;
	}


	.u-search-inner {
		background-color: #fff;
		width: 100%;
		height: 72rpx;
		border-radius: 40rpx;
		display: flex;
		align-items: center;
	}


	.addres {
		font-size: 24rpx;
		line-height: 42rpx;
		margin-left: 20rpx;
		width: 180rpx;

	}

	.title {
		font-size: 42rpx;
		font-weight: bold;
		color: #1B1B1B;
		line-height: 36rpx;
	}

	.contes {
		width: 100%;
		height: 100vh;
		background: url('@/static/homeimg/bgc.png') no-repeat;
		background-size: 100% 100%;
		overflow-x: hidden;
	}

	.bottomboder {
		border-bottom: 1px solid #f0f0f0;
	}

	.fontfamly {
		font-family: PingFang SC;
	}

	.imagebox {
		width: 108rpx;
		height: 82rpx;
		background: linear-gradient(0deg, #E3E3E3 0%, #F8F8F8 70%);
		border-radius: 30rpx 30rpx 40rpx 40rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.activeimagebox {
		background: linear-gradient(0deg, #F4CD8F 0%, #FFEAC9 70%);
		width: 108rpx;
		height: 82rpx;
		border-radius: 30rpx 30rpx 40rpx 40rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.boderedous {
		border-top-right-radius: 40rpx;
		border-bottom-right-radius: 40rpx;
	}

	.rededrl {
		border-top-left-radius: 10rpx;
		border-top-right-radius: 10rpx;
	}
</style>